import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { WebsocketService } from '@core/services/websocket/websocket.service';
import { Platform } from '@angular/cdk/platform';
import { ApiService } from '@core/services/http/api.service';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { Router } from '@angular/router';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';
import { InitService } from '@core/services/init.service';

@Component({
  selector: 'apes-login',
  templateUrl: './apes-login.component.html',
})
export class ApesLoginComponent {
  form: FormGroup;

  dialogRef: any = '';
  userId: any;
  _post: any = '';
   subject:any;

  constructor(fb: FormBuilder,
              private apiService: ApiService,
              private msg: ApesMessageService,
              private modalService: ApesModalService,
              private modal: ApesModalRef,
              private router: Router,
              private initService: InitService,
              private userAuthService: UserAuthService,
              private reuseTabService: ReuseTabService,
              private ws: WebsocketService,
              private platform: Platform) {

    this.form = fb.group({
      // userName: ['', [Validators.required, Validators.minLength(5)]],     // czy01
      password: ['', Validators.required],        // 123456
      // post: ['', [Validators.required]],
      // mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      // captcha: [null, [Validators.required]],
      // remember: [false],
    });
  }

  get password() {
    return this.form.controls.password;
  }

  openDialog(params: any, subject, callback?: any, dialog?: any) {
    this.subject = subject;
    const openDialog = dialog ? dialog : ApesLoginComponent;
    if (this.userAuthService.Login == true) {
      this.userAuthService.Login = false;
      this.dialogRef = this.modalService.create({
        apesWidth: 350,
        // apesVisible:true,
        apesMaskClosable: false,
        apesClosable: false,
        apesTitle: params.header.message,
        apesContent: openDialog,
        apesComponentParams: params,
        apesBodyStyle: {textAlign: 'right'},
        apesFooter: null,
      });
    } else {
      this.dialogRef.open();
    }
  }

  reLogin() {
    const userInfo = this.userAuthService.getUserInfoObj();
    this.userId = userInfo.userAccount.userId;
    this._post = userInfo.userAccount.post;
    const userModel = {
      userId: this.userId,
      password: this.form.controls.password.value,
      post: this._post,
      terminal: userInfo.userAccount.terminal,
    };
    this.sendLoginData(userModel);
  }

  sendLoginData(userModel) {

    this.apiService.post('aut.user.login', { 'body': JSON.stringify(userModel) })
      .subscribe((body) => {
        if (body) {
          let resultData = body.user;
          resultData['post'] = userModel.post;
          resultData['userId'] = userModel.userId;
          resultData['terminal'] = userModel.terminal;

          // 判断处于那个客户端
          let platform = this.userAuthService.getUserInfoObj() ? this.userAuthService.getUserInfoObj().platform : '';

          let userInfo = { 'token': body.sessionId, 'userAccount': resultData, 'terminal': userModel.terminal, 'platform': platform  };

          if (platform) {
            this.userAuthService.storeUserInfoLocal(JSON.stringify(userInfo));
            this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
          }else {
            this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
          }

          // 判断 当前的设备
          // if (this.platform.ANDROID) {
          //   // 将用户登录的信息存入 localStorage 中
          //   userInfo['userAccount'].password = userModel.password;
          //   this.userAuthService.storeUserInfoLocal(JSON.stringify(userInfo));
          //
          //   this.router.navigate(['pad']);
          // } else {

          // this.router.navigate(['']);

          // 清除复用路由导航
          // this.reuseTabService.clear();

          this.ws.connect(userInfo.userAccount.id);
          // }
          this.msg.success('已重新登录');
          this.userAuthService.Login = true;
          this.subject.next(body.sessionId);
          this.modal.destroy();

        } else {
          this.modal.open();
        }
      });
  }

}
